#Necessary Imports
import os
import sys
import string
from xml import sax
import re
import parser
from easysax import change

# Main function; The workhorse of EasyCMX
def main(ftp, host, user):
    
    # Set a null result string
    result = ""
    
    # Retrieve the users desired command
    cmd = raw_input("%s@%s: " %(user, host))
    cmd = cmd.strip()

    # Check the command in the following if/elif/else statements
    # Don't 'upper()' full command! Need to keep naming structure!
    
    # Next 3 if/elif's LS/DIR/LIST specified directory, current if none
    if (cmd[0:2].upper() == "LS"):
        directory = cmd[3:]
        try:
            ftp.cwd(directory)
            result = ftp.retrlines('LIST')
        except:
            result = "ERROR >> '" + directory + "' does not exist."        
    elif (cmd[0:3].upper() == "DIR"):   
        directory = cmd[4:]
        try:
            ftp.cwd(directory)
            result = ftp.retrlines('LIST')
        except:
            result = "ERROR >> '" + directory + "' does not exist."
    elif (cmd[0:4].upper() == "LIST"):   
        directory = cmd[5:]
        try:
            ftp.cwd(directory)
            result = ftp.retrlines('LIST')
        except:
            result = "ERROR >> '" + directory + "' does not exist."
        
    # Change to specified directory
    elif (cmd[0:2].upper() == "CD"):
        directory = cmd[3:]
        try:
            result = ftp.cwd(directory)
        except:
            result = "ERROR >> '" + directory + "' does not exist."
            
    # Delete the specified file/directory
    elif (cmd[0:3].upper() == "DEL"):
        if (cmd[0:6].upper() == "DELETE"):
            delete = cmd[7:]
        else:
            delete = cmd[4:]
        try:
            result = ftp.delete(delete)
        except:
            result = "ERROR >> '" + delete + "' does not exist."

    # Change local directory
    elif (cmd[0:3].upper() == "LCD"):
        directory = cmd[4:]
        try:
            os.chdir(directory)
            result = "Local directory changed to '" + os.getcwd() + "'"
        except:
            result = "ERROR >> '" + directory + "' does not exist."

    # List local directory
    elif (cmd[0:4].upper() == "LPWD"):
        directory = cmd[4:]
        try:
            result = "Local directory is '" + os.getcwd() + "'"
        except:
            result = "ERROR >> No working directory."

    # Get PWD of Server
    elif (cmd.upper() == "PWD"):
        result = ftp.pwd()
        
#    __FUTURE__
#    # Set Transfer Mode
#    elif (cmd.upper() == "ASCII" or cmd.upper() == "BINARY"):
#        result = ftp.transfercmd(cmd)

    # Retireve Size of specified file
    elif (cmd[0:4].upper() == "SIZE"):
        file = cmd[4:]
        # Make sure a filename is specified
        try:
            file = file.strip()
            result = ftp.size(file)
        except:
            result = "ERROR >> '" + file + "' does not exist."

    # Remove Specified directory
    elif (cmd[0:2].upper() == "RD"):
        directory = cmd[3:]
        try:
            result = ftp.rmd(directory)
        except:
            result = "ERROR >> '" + directory + "' does not exist."
    elif(cmd[0:5].upper() == "RMDIR"):
        directory = cmd[6:]
        try:
            result = ftp.rmd(directory)
        except:
            result = "ERROR >> '" + directory + "' does not exist."

    # Make a new directory
    elif (cmd[0:2].upper() == "MD"):
        directory = cmd[3:]
        result = ftp.mkd(directory)
    elif(cmd[0:5].upper() == "MKDIR"):
        directory = cmd[6:]
        result = ftp.mkd(directory)

    # Rename a file
    elif (cmd[0:3].upper() == "REN" and cmd[3] == " "):
        i = 4
        while (i < len(cmd)):
            if (cmd[i] == " "):
                space = i
                i = len(cmd)
                break
            else:
                i = i + 1
        before = cmd[4:space]
        after = cmd[space:]
        try:
            result = ftp.rename(before, after)
        except:
            result = "ERROR >> '" + before + "' does not exist."
    elif (cmd[0:6].upper() == "RENAME"):
        i = 7
        while (i < len(cmd)):
            if (cmd[i] == " "):
                space = i
                i = len(cmd)
                break
            else:
                i = i + 1
        before = cmd[7:space]
        after = cmd[space:]
        try:
            result = ftp.rename(before, after)
        except:
            result = "ERROR >> '" + before + "' does not exist."

    # CHMOD
    elif (cmd[0:5].upper() == "CHMOD"):
        perms = cmd[6:9]
        file = cmd[10:]
        try:
            result = ftp.voidcmd('SITE CHMOD ' + perms + ' ' + file)
        except:
           result = "ERROR >> '" + file + "' does not exist."

    # CREATE File
    elif (cmd[0:6].upper() == "CREATE"):
        file = cmd[7:]
        try:
            file = file.strip()
            if(re.search('.xml', file)):
                newfile = change(0)
                f = open(file, "r")
                ftp.storbinary('STOR ' + file, f)
                f.close()
                f = open('menu.xml', "r")
                ftp.storbinary('STOR menu.xml', f)
                f.close()
        except:
            result = "ERROR >> '" + file + "' cannot be created."

    # EDIT
#    elif (cmd[0:4].upper() == "EDIT"):

    # GET File
    elif (cmd[0:3].upper() == "GET"):
        file = cmd[4:]
        try:
            f = open(file, "wb")
            result = ftp.retrbinary('RETR ' + file, f.write, 8192)
            f.close()
            file = file.strip()
            print file
            if(re.search('.xml', file)):
                newfile = change(file)
                if(newfile != 0):
                    f = open(newfile, "r")
                    ftp.storbinary('STOR ' + newfile, f)
                    f.close()
        except:
            result = "ERROR >> '" + file + "' does not exist."
            
    elif (cmd[0:7].upper() == "INSTALL"):
        ftp.mkd('scripts')
        ftp.mkd('pages')
        ftp.mkd('styles')
        ftp.mkd('images')
        
        f = open('index.html', "r")
        ftp.storbinary('STOR index.html', f)
        f.close()
        f = open('menu.xml', "r")
        ftp.storbinary('STOR menu.xml', f)
        f.close()
        f = open('newsfeed.xml', "r")
        ftp.storbinary('STOR newsfeed.xml', f)
        f.close()
        f = open('template1.xsl', "r")
        ftp.storbinary('STOR template1.xsl', f)
        f.close()
        f = open('template2', "r")
        ftp.storbinary('STOR template2.xsl', f)
        f.close()
        
        ftp.cwd("pages")
        
        f = open('about.xml', "r")
        ftp.storbinary('STOR about.xml', f)
        f.close()
        f = open('contact.xml', "r")
        ftp.storbinary('STOR contact.xml', f)
        f.close()
        f = open('index.xml', "r")
        ftp.storbinary('STOR index.xml', f)
        f.close()
        f = open('news1.xml', "r")
        ftp.storbinary('STOR news1.xml', f)
        f.close()
        f = open('newsfeed.xml', "r")
        ftp.storbinary('STOR newsfeed.xml', f)
        f.close()
        

#    __FUTURE__
#    # MGET multiple files
#    elif (cmd[0:4].upper() == "MGET"):
#        # i counts till space, j counts between spaces, k counts number of entries in files tuple, l counts them out
#        i = 5
#        j = 5
#        k = 0
#        l = 0
#        files = ""
#        while (i < len(cmd)):
#            if (cmd[i] == " "):
#                start = i + 1
#                while (j < len(cmd)):
#                    if (cmd[j] == " "):
#                        end = j - 1
#                        j = len(cmd)
#                        break
#                    else:
#                        j = j + 1
#                files = files, cmd[start:end]
#                k = k + 1
#            else:
#               i = i + 1
#        while (l <= k):
#            f = open(files[l], "wb")
#            result = ftp.retrbinary('RETR ' + files[l], f.write, 8192)
#            f.close()
#            l = l + 1

    # PUT file - text < space = srcfile; file > space = destfile
    elif (cmd[0:3].upper() == "PUT"):
        file = cmd[4:]
        f = open(file, "r")
        result = ftp.storbinary('STOR ' + file, f)
        f.close()
        
#    __FUTURE__
#    # MPUT multiple files
#    elif (cmd[0:4].upper() == "MPUT"):
#        # i counts till space, j counts between spaces, k counts number of entries in files tuple, l counts them out
#        i = 5
#        j = 5
#        k = 0
#        l = 0
#        files = ""
#        while (i < len(cmd)):
#            if (cmd[i] == " "):
#                start = i + 1
#                while (j < len(cmd)):
#                    if (cmd[j] == " "):
#                        end = j - 1
#                        j = len(cmd)
#                        break
#                    else:
#                        j = j + 1
#                files = files, cmd[start:end]
#                k = k + 1
#            else:
#               i = i + 1
#        while (l <= k):
#            f = open(files[l], "r")
#            result = ftp.storbinary('STOR ' + files[l], f)
#            f.close()
#            l = l + 1
        
    # Display the FTP Server's Help
    elif (cmd.upper() == "?" or cmd.upper() == "HELP"):
        result = ftp.sendcmd("HELP")
    
    # Display EasyCMX's help
    elif (cmd.upper() == "--HELP"):
        pathname = os.path.dirname(sys.argv[0])
        pathname = os.path.abspath(pathname)
        readme = pathname + "\\README"
        f = open(readme, "r")
        show = 532
        print "\n"
        lines = f.read(show)
        while (lines != ""):
            print lines
            prompt = raw_input("Hit Return for more, or q (and Return) to quit: ")
            prompt = prompt.strip()
            if prompt == "":
                show = show + 532
            elif prompt.upper() == "Q":
                break
            lines = f.read(show)
        f.close()
        result = ""

    # Quit
    elif (cmd.upper() == "QUIT" or cmd.upper() == "BYE" or cmd.upper() == "CLOSE" or cmd.upper() == "EXIT"):
        ftp.quit()
        sys.exit(0)

    # Handle blank commands
    elif cmd == "":
        result = ""

    # Handle unsupported commands
    else:
        result = "ERROR >> Command '" + cmd + "' is unsupported"

    # Print the results of whatever command(s) was executed
    print result

    # Restart the process...
    main(ftp, host, user)
